#include('/header.html', {title : '资料管理'})
<body class="es-main-default es-nav-default ">

<div class="es-wrap">
  <div id="content-container" class="container">
    #include('header.html')
    <div class="row">
      <div class="col-md-3">
        <div class="sidenav locked js-sidenav" data-course-length="1">
          #include('sideMenu.html', {material : 'active'})
        </div>
      </div>
      <div class="col-md-9" id="material-box">
        <div class="panel panel-default panel-col">
          <div class="panel-heading">
            <a href="#" data-toggle="modal" data-target="#createNotice"
               class="btn btn-info btn-sm pull-right mls">
              <span class="es-icon es-icon-anonymous-iconfont"></span>上传资料</a>
            资料管理
          </div>
          <div class="panel-body " id="quiz-table-container">
            <table class="table table-striped table-hover" id="quiz-table">
              <thead>
              <tr>
                <th>序号</th>
                <th>名称</th>
                <th>从属于</th>
                <th>下载人数</th>
                <th>创建时间</th>
                <th>操作</th>
              </tr>
              </thead>
              <tbody>
              <tr v-if="materials.length<=0">
                <td colspan="7" class="empty">暂无资料</td>
              </tr>
              <tr is="mater-tr" v-for="(material, index) in materials" :key="material.id"
                  :material="material" :index="index"></tr>
              </tbody>
            </table>
            <div v-if="page.totalPages > 1" class="text-center">
              <navigation :pages="page.totalPages" :current.sync="page.pageNum" @navpage="gotoPage"/>
            </div>
          </div>
        </div>

        <input type="file" accept=".doc,.docx,.pptx,.pdf,.zip,.rar"
               class="hide" ref="file_in">
        <!--创建试卷的模态框-->
        <div class="modal fade" id="createNotice" role="dialog" tabindex="-1" aria-labelledby="myModalLabel">
          <div class="modal-dialog">
            <div class="modal-content">
              <div class="modal-header">
                <button class="close" onclick="hideM(true);">
                  x
                </button>
                <h4 class="modal-title">文件上传</h4>
              </div>
              <div class="modal-body">
                <form id="announcement-create-form" class="form-horizontal" onsubmit="return false;">
                  <div class="row form-group">
                    <div class="col-sm-3 control-label">
                      <label for="name">资料名称</label>
                    </div>
                    <div class="col-sm-8 controls">
                      <div class="input-group">
                        <input disabled
                             v-model="material.filename" id="name" class="form-control">
                        <span class="input-group-addon">{{material.fileType}}</span>
                      </div>
                    </div>
                  </div>
                  <div class="row form-group">
                    <div class="col-sm-3 control-label">
                      <label for="belong">所属课程</label>
                    </div>
                    <div class="col-sm-8 controls">
                      <select id="belong" v-model="material.taskId" class="form-control width-input width-input-large">
                        <option value="0" selected="selected">[默认教学计划]</option>
                        <option v-for="(ta, index) in tasks" :value="ta.id" :data-index="index">{{ta.name}}</option>
                      </select>
                    </div>
                  </div>
                  <div class="col-sm-8 col-sm-offset-3" v-if="progress>=0">
                    <div class="progress progress-striped">
                      <div class="progress-bar progress-bar-success" :style="'width:' + progress + '%'">
                        <span>{{progress}}%</span>
                      </div>
                    </div>
                  </div>
                  <div class="row form-group">
                    <div class="col-sm-3 control-label">
                      <label>上传试卷</label>
                    </div>
                    <div class="col-sm-8">
                      <div ref="upload_mater" class="uploader-content">
                        <div class="uploader-container text-center"
                             v-html="material.path!=null?'<font color=green>文件已保存！</font>'
                             :'文件上传(支持word,pdf,ppt,zip...)!'"></div>
                      </div>
                    </div>
                  </div>
                </form>
              </div>
              <div class="modal-footer">
                <button @click="save_" class="btn btn-primary">确定上传</button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
<template id="mater-tr">
  <tr>
    <th>{{index+1}}</th>
    <td>{{material.filename}}</td>
    <td>{{material.task==null?'默认教学计划':material.task.name}}</td>
    <td>{{material.downs}}</td>
    <td>{{material.time.substr(0,16)}}</td>
    <td>
      <button @click="delete_" class="btn btn-danger btn-xs">删除</button>
    </td>
  </tr>
</template>
<script>
  var materVm = new Vue({
    el: '#material-box',
    data: {
      tasks: [],
      material: {
        courseId: 0,
        taskId: 0,
        filename: null,
        path: null
      },
      materials: [],
      progress: -1,
      page: {
        pageNum: 1,
        totalPages: 1,
        limit: 10
      }
    },
    watch: {
      'page.pageNum': function (nv) {
        this.getMaterials();
      }
    },
    methods: {
      gotoPage: function (page) {
        this.page.pageNum = page;
      },
      getMaterials: function () {
        var self = this;
        $.post('/course/material/api/${kid}/page', {type: 0, page: self.page.pageNum}, function (data) {
          if (data.success) {
            self.materials = data.payload.rows;
            self.page.limit = data.payload.limit;
            self.page.pageNum = data.payload.pageNum;
            self.page.totalPages = data.payload.totalPages;
          }
        });
      },
      save_: function () {
        if (this.checkForm()) {
          var self = this;
          self.material.filename = self.material.filename + self.material.fileType;
          var opt = $('#belong').find('option:checked');
          var index = opt.data('index');
          var task = self.tasks[index];
          $.post('/course/set/material/${kid}/save', self.material, function (data) {
            if (data.success) {
              var mat = data.payload;
              mat.task = task;
              self.materials.unshift(mat);
              if (self.materials.length > self.page.limit) self.getMaterials();
              layer.msg('保存成功！', {time: 1200, icon: 6});
              hideM();
            }
          });
        }
      },
      checkForm: function () {
        var mat = this.material;
        if (isEmpty(mat.filename)) {
          layer.msg("资料名不能为空！", {time: 1200});
        } else if (isEmpty(mat.path)) {
          layer.msg("资料必须上传！", {time: 1200});
        } else return true;
        return false;
      }
    },
    components: {
      'mater-tr': {
        props: ['material', 'index'],
        template: '#mater-tr',
        methods: {
          delete_: function () {
            var self = this;
            layer.confirm('确定删除？删除后将无法找回！', {
              icon: 5, title: '提示'
            }, function (i) {
              $.post("/course/set/material/api/${kid}/delete/" + self.material.id, {other: true}, function (data) {
                console.log(data);
                if (data.success) {
                  self.$root.materials.splice(self.index, 1);
                  if (self.$root.materials.length <= 0) self.$root.page.pageNum--;
                  self.$root.getMaterials();
                  layer.msg('删除成功！', {icon: 6, time: 1200});
                  layer.close(i);
                }
              });
            });
          }
        }
      }
    },
    created: function () {
      var self = this;
      self.getMaterials();
      $.post('/course/task/api/${kid}/page', {size: 10000, status: 1}, function (data) {
        if (data.success) {
          self.tasks = data.payload.rows;
        }
      })
    },
    mounted: function () {
      var self = this;
      self.$refs.upload_mater.onclick = function () {
        self.$refs.file_in.click();
      };
      self.$refs.file_in.onchange = function (e) {
        var inp = e.target;
        var file = inp.files[0];
        upload_(file, self.material.taskId, function (data) {
          if (data.success) {
            $('#name').prop("disabled", false);
            self.material = data.payload.payload;
            var fn = self.material.filename;
            var last = fn.lastIndexOf(".");
            var name = fn.substring(0, last);
            var type = fn.substring(last);
            self.material.filename = name;
            self.material.fileType = type;
            console.log(self.material);
          }
        });
      };
    }
  });

  function upload_(file, tid, fun) {
    materVm.progress = 0;
    var fd = new FormData();
    fd.append('file', file);
    fd.append('type', 'material');
    fd.append('kid', '${kid}');
    fd.append('tid', tid);
    var xhr = new XMLHttpRequest();
    xhr.open('post', '/file/t/upload/', true);
    xhr.onload = function () {
      var data = JSON.parse(xhr.responseText);
      materVm.$refs.file_in.value = null;
      fun ? fun(data) : null;
    };
    xhr.upload.onprogress = function (ev) {
      materVm.progress = parseInt(ev.loaded / ev.total * 100);
    };
    xhr.send(fd);
  }

  $('#createNotice').on('hidden.bs.modal', function () {
    $('#name').prop("disabled", true);
    materVm.material = {id: 0, path: null, filename: null, courseId: 0, taskId: 0};
    materVm.$refs.file_in.value = null;
    materVm.progress = -1;
  });

  function hideM(tip) {
    if (tip) {
      layer.confirm('退出后未保存的数据将丢失！确定退出？', {icon: 5, title: '警告'}, function (i) {
        $('#createNotice').modal('hide');
        layer.close(i);
      });
    } else {
      $('#createNotice').modal('hide');
    }
  }
</script>
#include('/footer.html')